import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    cart: JSON.parse(localStorage.getItem('cart') || '[]')
  },
  getters: {
    isLogin: state => !!state.token,
    userInfo: state => state.userInfo,
    userRole: state => state.userInfo.role || '',
    cartCount: state => state.cart.reduce((total, item) => total + item.quantity, 0),
    cartTotal: state => state.cart.reduce((total, item) => total + (item.price * item.quantity), 0)
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
      console.log('设置token:', token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      console.log('设置用户信息:', userInfo)
    },
    clearUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      console.log('清除用户信息')
    },
    addToCart(state, product) {
      // 检查商品是否已存在购物车
      const index = state.cart.findIndex(item => 
        item.id === product.id && item.merchantId === product.merchantId
      )
      if (index > -1) {
        // 已存在，更新数量
        state.cart[index].quantity += product.quantity
      } else {
        // 不存在，添加到购物车
        state.cart.push(product)
      }
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    updateCartItem(state, { index, quantity }) {
      state.cart[index].quantity = quantity
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    removeCartItem(state, index) {
      state.cart.splice(index, 1)
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    clearCart(state) {
      state.cart = []
      localStorage.removeItem('cart')
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      commit('setToken', userInfo.token)
      commit('setUserInfo', userInfo)
    },
    // 注销
    logout({ commit }) {
      commit('clearUserInfo')
      commit('clearCart')
    },
    // 添加到购物车
    addToCart({ commit, state }, product) {
      // 检查是否来自同一商家
      if (state.cart.length > 0 && state.cart[0].merchantId !== product.merchantId) {
        // 先清空购物车，再添加
        commit('clearCart')
      }
      commit('addToCart', product)
    }
  },
  modules: {
  }
}) 